#!/usr/bin/env pypy

#
# Copyright 2016 HNSDFZ
#

import os
import sys
import urllib2

def catch(link, save_to):
    print("(info) Catching {}...".format(idx))

    try:
        response = urllib2.urlopen(link)

        with open(save_to, "w") as file:
            file.write(response.read())

        response.close()
    except Exception as e:
        print("(error) Error when catching {}: {}".format(
            idx, str(e)
        ))


if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Usage: {} [START] [END]".format(sys.argv[0]))
        exit(-1)

    start = int(sys.argv[1])
    end = int(sys.argv[2])
    link = "http://218.28.19.228/cogs/problem/problem.php?pid={id}"
    save_to = "./cogs/"

    for idx in range(start, end + 1):
        if not os.path.exists("{}{}/".format(save_to, idx)):
            os.mkdir("{}{}/".format(save_to, idx))

        catch(
            link.format(id = idx),
            "{}{}/page.html".format(save_to, idx)
        )
